/*
+--------------------------
| FreeloaderOS v0.0.1
|  - Microkernel
+--------------------------
| Written by Alec Hussey
| Copyright (c) 2007
|  - Deus X Foundation
+---------------------------
*/

/*
 * Standard C Library
 */

#include <system.h>
#include <math.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>

#define BLOCK 1024;

/*
Memory Struct
*/
static union header
{
	struct
	{
		union header *link;
		unsigned size;
	} s;
	union align
	{
		double d;
		unsigned u;
		void (*f)(void);
	} x;
} freelist = {&freelist, 0}, *freep = &freelist;

extern void sbrk();
/*
void *malloc(unsigned num_bytes)
{
	union header *p, *q;
	unsigned size = (num_bytes + sizeof(union header) - 1) / sizeof(union header) + 1;
	
	q = freep;
	do
	{
		p = p->s.link;
		if (p->s.size > size)
		{
			p->s.size -= size;
			p += p->s.size;
			p->s.size = size;
			freep = q;
			return p + 1;
		}
		else if (p->s.size == size)
		{
			q->s.link = p->s.link;
			freep = q;
			return p + 1;
		}
		q = p;
	}
	while (p != freep);
	
	if (size < BLOCK)
		size = BLOCK;
	
	p = sbrk(size*sizeof *p);
	
	if (p == (void*)-1)
		return 0;
	
	p->s.size = size;
	return malloc(num_bytes);
}

void free(void *pointer)
{
	union header *bp = (union header*) pointer - 1, *p;
	
	if (pointer == NULL)
		return;
	
	for (p = freep; ; p = p->s.link)
		if (bp > p && bp < p->s.link
			|| p >= p->s.link && (bp > p 
			|| bp < p->s.link))
			break;
	
	if (bp + bp->s.size == p->s.link)
	{
		bp->s.size += p->s.link->s.size;
		bp->s.link = p->s.link->s.link;
	}
	else
	{
		bp->s.link = p->s.link;
	}
	
	if (p + p->s.size == bp)
	{
		p->s.size += bp->s.size;
		p->s.link = bp->s.link;
	}
	else
	{
		p->s.link = bp;
	}
	freep = p;
}
*/
/*
Find the hexadecimal value of a
given string.
*/
unsigned char atoh(unsigned char *str)
{
	int i;
	int lenval = strlen(str);
	long int powval;
	unsigned char retval = 0;
	
	for (i = 0; i < lenval; i++)
	{
		if ((str[i] > 48+9) || (str[i] < 48))
			return 0;
		
		powval = (str[lenval-(i+1)]-48) * pow(16, i);
		retval = retval + powval;
	}
	return retval;
}
